import express from 'express';
import path from 'path';
import fs from 'fs';

const app = express();

// 设置跨域请求头
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});
app.use(express.json());
app.use(express.static(path.join(path.resolve(), './views')));

app.get('/', (req, res) => {
    res.sendFile(path.join(path.resolve(), './views/index.html'));
});

app.post('/api/user', (req, res) => {
    try {
        const userList = fs.readFileSync('./data/userlist.json', 'utf-8')
        const userData = JSON.parse(userList);
        console.log(req.body);

        if (!req.body.userIds) {
            return res.status(404).json({
                error: 'param userId not found'
            });
        }
        const users = userData.userlist.map(element => {
            if (req.body.userIds.includes(element.id)) {
                return element;
            } else {
                return {
                    ...element,
                    name: ''
                }
            }
        });
        res.json(users || []);
    } catch (err) {
        console.log(err);
        res.status(500).json({
            error: err.message
        });
    }
})

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});
